#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> allPossibleFBT(int n)
    {
        if (n % 2 == 0) {
            return std::vector<TreeNode*>();
        }

        return _allPossibleFBT(1, n);
    }

private:
    std::vector<TreeNode*> _allPossibleFBT(int left, int right)
    {
        std::vector<TreeNode*> ret;

        if (left == right) {
            TreeNode* root = new TreeNode(0);
            ret.push_back(root);
            return ret;
        }
        else if (left > right)
        {
            ret.push_back(nullptr);
            return ret;
        }

        for (int mid = left + 1; mid <= right; mid += 2)
        {
            std::vector<TreeNode*> lefts = _allPossibleFBT(left, mid - 1);
            std::vector<TreeNode*> rights = _allPossibleFBT(mid + 1, right);

            for (TreeNode* left : lefts)
            {
                for (TreeNode* right : rights)
                {
                    TreeNode* root = new TreeNode(0);
                    root->left = left;
                    root->right = right;
                    ret.push_back(root);
                }
            }
        }

        return ret;
    }
};